import pyautogui as pg
import os
import time
import pyperclip
import requests
import json
import psutil
import sys
import win32gui, win32com.client
import win32api
import win32con
import win32process  
import ctypes
import re
import shutil
from pywinauto.application import Application

def check_qdy_qdg(file_name):
    file_name_split = file_name.split('.')
    file_ext = file_name_split[-1].lower()
    file_pre = file_name_split[0].lower()
    return file_pre, file_ext


def qdy_open_file(file_pre, file_path):
    hwnd = win32gui.FindWindow(None, "斯维尔清单计价 TH-BQ2016 标准版")
    tutor_hwnd = win32gui.FindWindow(None, "新建向导")
    # 获取屏幕分辨率  
    screen_width = win32api.GetSystemMetrics(win32con.SM_CXSCREEN)  
    screen_height = win32api.GetSystemMetrics(win32con.SM_CYSCREEN)  

    # 获取窗口当前位置和大小  
    left, top, right, bottom = win32gui.GetWindowRect(tutor_hwnd)  
    window_width = right - left  
    window_height = bottom - top  

    # 计算新位置  
    new_left = (screen_width - window_width) // 2  
    new_top = (screen_height - window_height) // 2  

    # 移动窗口  
    win32gui.SetWindowPos(tutor_hwnd, win32con.HWND_TOP, new_left, new_top, window_width, window_height, 0)

    left, top, right, bottom = win32gui.GetWindowRect(tutor_hwnd) 


    print(str(left) + " " + str(top) + " " + str(right) + " " + str(bottom))

    pg.click((right - left) * (1 * (1.75 / 5)) + left, (bottom - top) * ((1.0 / 6) * 1) + top)

    # pg.typewrite("测试建设项目")
    time.sleep(1)


    new_construct = win32gui.FindWindow(None, "新建建设项目文件")
    child_windows = []  
    win32gui.EnumChildWindows(new_construct, enum_child_windows, child_windows)  
    # print(len(child_windows))
    # 假设我们找到了一个类名为 'EDIT' 的子窗口（通常编辑框的类名）  
    edit_hwnd = None  
    confirm_hwnd = None
    for hwnd_child, window_text_child in child_windows:  
        # print(str(hwnd_child) + " " + win32gui.GetClassName(hwnd_child) + " " + win32gui.GetWindowText(hwnd_child))
        # print(win32gui.GetClassName(hwnd_child) + " " + win32gui.GetWindowText(hwnd_child))
        if win32gui.GetClassName(hwnd_child) == 'TEdit':  
            edit_hwnd = hwnd_child 
    win32gui.SendMessage(edit_hwnd, win32con.WM_SETTEXT, 0, file_pre)
    pg.hotkey("enter")
    pg.hotkey("enter")
    pg.hotkey("enter")
    pg.hotkey("enter")
    pg.hotkey("enter")
    pg.hotkey("enter")
    pg.hotkey("enter")
    pg.hotkey("enter")
    time.sleep(1)
    pg.hotkey("enter")
    time.sleep(1)
    is_sure = win32gui.FindWindow(None, "确认另存为")
    if is_sure:
        pg.hotkey("left")
        pg.hotkey("enter")
    time.sleep(5)
    pg.hotkey("tab")
    pg.hotkey("tab")
    pg.hotkey("shift", "f10")
    pg.hotkey("e")


    pg.hotkey("shift", "f10")
    pg.hotkey("s")
    time.sleep(5)
    open = win32gui.FindWindow(None, "打开")
    if open:
        # win32gui.ShowWindow(hwnd, win32con.SW_MAXIMIZE)
        print(f"打开窗口句柄为：{open}")
        time.sleep(1)
    else:
        print("打开未找到指定窗口")
    child_windows = []  
    win32gui.EnumChildWindows(open, enum_child_windows, child_windows)  
    # print(len(child_windows))
    # 假设我们找到了一个类名为 'EDIT' 的子窗口（通常编辑框的类名）  
    edit_hwnd = None  
    confirm_hwnd = None
    for hwnd_child, window_text_child in child_windows:  
        # print(str(hwnd_child) + " " + win32gui.GetClassName(hwnd_child) + " " + win32gui.GetWindowText(hwnd_child))
        if win32gui.GetClassName(hwnd_child) == 'Edit':  
            edit_hwnd = hwnd_child  
    win32gui.SendMessage(edit_hwnd, win32con.WM_SETTEXT, 0, file_path)
    set_foreground_window(open)
    # win32gui.SetFocus(open)
    pg.hotkey("Enter")
    return hwnd

def enum_child_windows(hwnd, result):  
    result.append((hwnd, win32gui.GetWindowText(hwnd)))  

def set_foreground_window(hwnd):  
    try :
        _, pid = win32process.GetWindowThreadProcessId(hwnd)  
        ctypes.windll.user32.AllowSetForegroundWindow(pid)  
        shell = win32com.client.Dispatch("WScript.Shell")
        shell.SendKeys('%{1}')
        win32gui.SetForegroundWindow(hwnd)  
    except Exception as e:
        return

def reset_softWare_Default():
    time.sleep(7)
    pg.hotkey("tab")
    pg.hotkey("tab")
    pg.hotkey("shift", "F10")
    pg.hotkey("up")
    pg.hotkey("enter")
    time.sleep(1)
    pg.hotkey("right")
    pg.hotkey("enter")
    pg.hotkey("left")
    pg.hotkey("enter")
    pg.hotkey("right")
    pg.hotkey("enter")

# 升级qdg3到qdg4
def check_sure_upgrade():
    time.sleep(1)
    sure = win32gui.FindWindow(None, "确认")
    if sure:
        pg.hotkey("enter")
        time.sleep(10)


def check_project_number_is_null():
    time.sleep(5)
    # pg.hotkey("tab")
    # pg.hotkey("tab")
    pyperclip.copy("2")
    pg.hotkey("right")
    time.sleep(1)
    pg.hotkey("right")
    # 解锁单元格
    pg.hotkey("shift", "F10")
    pg.hotkey("w")
    pg.hotkey("space")
    pg.hotkey("ctrl", "c")
    number = pyperclip.paste()
    if number != "2" :
        return
    else :
        i = 1
        retry = 0
        while True :
            pyperclip.copy("2")
            pg.hotkey("ctrl", "c")
            pre_number = pyperclip.paste()
            if (pre_number != "2" and pre_number != " " and pre_number != "  ") :
                retry += 1
                i -= 1
                if retry >= 2 :
                    break
            # pyperclip.copy("1")
            time.sleep(0.5)
            # pg.hotkey("ctrl", "v")
            pg.typewrite("1")
            if i == 1 :
                pyperclip.copy("2")
                # 检测是否输入成功
                time.sleep(1)
                pg.hotkey("ctrl", "a")
                pg.hotkey("ctrl", "c")
                # print(pyperclip.paste())none
                if (pyperclip.paste() != "1") :
                    pg.hotkey("enter")
                    pg.hotkey("right")
                    time.sleep(0.5)
                    # 解锁单元格
                    pg.hotkey("shift", "F10")
                    pg.hotkey("w")
                    pg.hotkey("space")
                    continue
            pg.hotkey("enter")
            pg.hotkey("down")
            time.sleep(0.5)
            # 解锁单元格
            pg.hotkey("shift", "F10")
            pg.hotkey("w")
            pg.hotkey("space")
            time.sleep(0.5)
            if i > 200:
                raise Exception('too many project numbers need to be filled in')
            i += 1


# 扫描指定目录下的文件，运行名称里有QDJJ或者以斯维尔清单开头的文件
def open_software(dir_path) :
    file_list = os.listdir(dir_path)
    list = []
    for file_name in file_list :
        if (file_name.startswith("斯维尔清单") or "QDJJ" in file_name):
            list.append(file_name)
    os.startfile(dir_path + "\\" + list[0])


def close_tips():
    time.sleep(7)
    tips = win32gui.FindWindow(None, "提示")
    if tips:
        # win32gui.ShowWindow(hwnd, win32con.SW_MAXIMIZE)
        print(f"窗口句柄为：{tips}")
        title = win32gui.GetWindowText(tips)
        clsname = win32gui.GetClassName(tips)
        print(title + clsname)
        win32gui.SendMessage(tips, win32con.WM_CLOSE, 0, 0)
    else:
        print("tips : 未找到指定窗口")
        # raise Exception('tips : 未找到指定窗口句柄')

def close_tutor():
    time.sleep(3)
    tutor = win32gui.FindWindow(None, "新建向导")
    if tutor:
        win32gui.SendMessage(tutor, win32con.WM_CLOSE, 0, 0)
        print(f"窗口句柄为：{tutor}")
    else:
        print("新建向导 : 未找到指定窗口")
    tutor = win32gui.FindWindow(None, "新建向导")
    if tutor:
        win32gui.SendMessage(tutor, win32con.WM_CLOSE, 0, 0)
        print(f"窗口句柄为：{tutor}")
    else:
        print("新建向导 : 未找到指定窗口")

def open_file(target_file_path):
    if not os.path.exists(target_file_path) :
        raise Exception ("cant not find file")
    hwnd = win32gui.FindWindow(None, "斯维尔清单计价 TH-BQ2016 标准版")
    if hwnd:
        # win32gui.ShowWindow(hwnd, win32con.SW_MAXIMIZE)
        print(f"窗口句柄为：{hwnd}")
    else:
        print("未找到指定窗口")
    menu = win32gui.GetMenu(hwnd)
    menu1 = win32gui.GetSubMenu(menu, 0)#第几个菜单
    cmd_ID = win32gui.GetMenuItemID(menu1, 1)#第几个子菜单
    win32gui.PostMessage(hwnd, win32con.WM_COMMAND, cmd_ID, 0)
    time.sleep(2)
    open = win32gui.FindWindow(None, "打开")
    if open:
        # win32gui.ShowWindow(hwnd, win32con.SW_MAXIMIZE)
        print(f"打开窗口句柄为：{open}")
        time.sleep(1)
    else:
        print("打开未找到指定窗口")
    child_windows = []  
    win32gui.EnumChildWindows(open, enum_child_windows, child_windows)  
    # print(len(child_windows))
    # 假设我们找到了一个类名为 'EDIT' 的子窗口（通常编辑框的类名）  
    edit_hwnd = None  
    confirm_hwnd = None
    for hwnd_child, window_text_child in child_windows:  
        # print(str(hwnd_child) + " " + win32gui.GetClassName(hwnd_child) + " " + win32gui.GetWindowText(hwnd_child))
        if win32gui.GetClassName(hwnd_child) == 'Edit':  
            edit_hwnd = hwnd_child  
    win32gui.SendMessage(edit_hwnd, win32con.WM_SETTEXT, 0, target_file_path)
    set_foreground_window(open)
    # win32gui.SetFocus(open)
    pg.hotkey("Enter")
    time.sleep(3)
    return hwnd


def check_version():
    time.sleep(5)
    version_tips = win32gui.FindWindow(None, "提示")
    if (version_tips is not None and version_tips != 0):
        # app = Application(backend='uia').connect(handle=version_tips)
        # dlg = app.window(title=win32gui.GetWindowText(version_tips))  
        # static_control = dlg.child_window(control_type="Text", found_index=1)  # found_index可能需要根据实际情况调整  
        # text = static_control.window_text()
        # raise Exception(text)
        raise Exception('计价文件无法打开')
        win32gui.SendMessage(version_tips, win32con.WM_CLOSE, 0, 0)

def check_precision():
    time.sleep(5)
    check = win32gui.FindWindow(None, "询问")
    print("询问" + str(check))
    if check:
        pg.hotkey("Enter")
        i = 0
        while (i < 300):
            suc_tips = win32gui.FindWindow(None, "提示")
            print("询问结束 提示：" + str(suc_tips))
            if suc_tips:
                win32gui.SendMessage(suc_tips, win32con.WM_CLOSE, 0, 0)
                pg.hotkey("Enter")
                break;
            i = i + 1
            time.sleep(5)


def export_file_twice(hwnd):
    time.sleep(1)
    result = win32gui.FindWindow(None, "数据检测结果")
    if result:
        win32gui.SendMessage(result, win32con.WM_CLOSE, 0, 0)
    y_hwnd = win32gui.FindWindow(None, "导出为辅助评标标准接口文件")
    if y_hwnd:
        win32gui.SendMessage(y_hwnd, win32con.WM_CLOSE, 0, 0)
    time.sleep(3)
    pg.hotkey("down")

    app = Application(backend='uia').connect(handle=hwnd)
    dlg = app.window(title=win32gui.GetWindowText(hwnd))  # 根据你的窗口标题进行调整  
    generate = dlg.child_window(title="生成标书", control_type="Button")
    generate.click_input()
    
    time.sleep(1)
    x_hwnd = win32gui.FindWindow(None, "导出为辅助评标标准接口文件")
    app = Application(backend='uia').connect(handle=x_hwnd)
    dlg = app.window(title=win32gui.GetWindowText(x_hwnd))  # 根据你的窗口标题进行调整  

    button = dlg.child_window(title="控制价文件", control_type="RadioButton")
    button.click_input()



    pg.hotkey("Enter")
    time.sleep(2)
    number_eror = win32gui.FindWindow(None, "提示")
    if number_eror is not None and number_eror != 0:
        raise Exception('计价文件导出错误')


def export_file(hwnd, file_ext):
    time.sleep(5)
    app = Application(backend='uia').connect(handle=hwnd)
    dlg = app.window(title=win32gui.GetWindowText(hwnd))  # 根据你的窗口标题进行调整  

    elec_book = dlg.child_window(title="电子标书", control_type="TabItem")
    elec_book.click_input()

    time.sleep(1)
    pg.hotkey("tab")
    pg.hotkey("tab")
    if (file_ext == 'qdy3' or file_ext == 'qdy4') :
        pg.hotkey("tab")
        # pg.hotkey("tab")
    time.sleep(1)
    pg.hotkey("up")
    time.sleep(1)
    pg.hotkey("up")

    generate = dlg.child_window(title="生成标书", control_type="Button")
    generate.click_input()
    
    x_hwnd = win32gui.FindWindow(None, "导出为辅助评标标准接口文件")
    app = Application(backend='uia').connect(handle=x_hwnd)
    dlg = app.window(title=win32gui.GetWindowText(x_hwnd))  # 根据你的窗口标题进行调整  

    button = dlg.child_window(title="控制价文件", control_type="RadioButton")
    button.click_input()

    pg.hotkey("Enter")
    time.sleep(2)
    
    
def fill_author_info():
    ppp = 0
    time.sleep(3)
    author_hwnd = win32gui.FindWindow(None, "项目信息检测")
    another = win32gui.FindWindow(None, "另存为")
    result = win32gui.FindWindow(None, "数据检测结果")
    while ppp < 10 and not author_hwnd and not another and not result:
        time.sleep(3)
        author_hwnd = win32gui.FindWindow(None, "项目信息检测")
        another = win32gui.FindWindow(None, "另存为")
        result = win32gui.FindWindow(None, "数据检测结果")
        ppp += 1

    print("项目信息" + str(author_hwnd))
    if (author_hwnd) :
        pg.hotkey("right")
        count = 0
        while True :
            pyperclip.copy("1")
            pg.hotkey("ctrl", "v")
            pg.hotkey("enter")
            pg.hotkey("down")
            pg.hotkey("space")
            count += 1
            if (count > 6):
                break
        pg.hotkey("tab")
        pg.hotkey("enter")


def do_export(id, hwnd, count):
    if (count > 3):
        raise Exception("recur_error")
    time.sleep(3)
    another = win32gui.FindWindow(None, "另存为")
    result = win32gui.FindWindow(None, "数据检测结果")
    # error2 = win32gui.FindWindow(None, "斯维尔清单计价 TH-BQ2016 标准版")
    if result:
        export_file_twice(hwnd)
        fill_author_info()
        xml_file_name = do_export(id, hwnd, count + 1)
        return xml_file_name
    
    times = 0
    while not another and not result and times < 40:
        time.sleep(3)
        another = win32gui.FindWindow(None, "另存为")
        result = win32gui.FindWindow(None, "数据检测结果")
        # error2 = win32gui.FindWindow(None, "斯维尔清单计价 TH-BQ2016 标准版")
        times += 1

    if result:
        export_file_twice(hwnd)
        fill_author_info()
        xml_file_name = do_export(id, hwnd, count + 1)
        return xml_file_name
        
    # child_windows = []  
    # print(len(child_windows))
    # 假设我们找到了一个类名为 'EDIT' 的子窗口（通常编辑框的类名）  
    if another:
        time.sleep(0.5)
        xml_file_name = str(id) + ".swt"
        set_foreground_window(another)
        pg.typewrite(xml_file_name)
        time.sleep(0.5)
        pg.hotkey("enter")
        error = win32gui.FindWindow(None, "错误")
        if error:
            win32gui.SendMessage(error, win32con.WM_CLOSE, 0, 0)
            export_file_twice(hwnd)
            fill_author_info()
            xml_file_name = do_export(id, hwnd, count + 1)
            return xml_file_name
        time.sleep(1)
        confirm = win32gui.FindWindow(None, "确认另存为")
        if confirm:
            pg.hotkey("left")
            pg.hotkey("enter")
    else :
        raise Exception("当前处理的工程文件数据内出现内部未知错误")
    return xml_file_name

def check_success(id, hwnd, count):
    if (count > 2) :
        raise Exception("recur_error")
    while True :
        time.sleep(5)
        # 导出成功
        success_hwnd = win32gui.FindWindow(None, "提示")
        if success_hwnd:
            return
        error = win32gui.FindWindow(None, "错误")
        error2 = win32gui.FindWindow(None, "斯维尔清单计价 TH-BQ2016 标准版")
        if error or error2:
            print("找到错误信息")
            win32gui.SendMessage(error, win32con.WM_CLOSE, 0, 0)
            export_file_twice(hwnd)
            fill_author_info()
            do_export(id, hwnd, 0)
            check_success(id, hwnd, count + 1)


# 关闭软件
def close_software():
    time.sleep(10)
    pids = psutil.pids()
    for pid in pids:
        p = psutil.Process(pid)
        process_name = p.name()
        if process_name.startswith('QDJJ'):
            # 杀掉指定进程
            # print('kill process: name: %s - pid: %s' %(process_name, pid))
            find_kill = 'taskkill -f -pid %s' % pid
            os.popen(find_kill)


def open_software_golden(dir_path) :
    file_list = os.listdir(dir_path)
    list = []
    for file_name in file_list :
        if (file_name.startswith("广联达") or "GCCP" in file_name):
            list.append(file_name)
    os.startfile(dir_path + "\\" + list[0])


def find_latest_swt_file_golden(directory):  
    latest_swt_file = None  
    latest_mtime = 0  
  
    # 遍历目录  
    for root, dirs, files in os.walk(directory):  
        for file in files:  
            # 检查文件是否以.swt结尾  
            print(file)
            if file.endswith('.SWT') or file.endswith('.swt'):  
                # 获取文件的完整路径  
                file_path = os.path.join(root, file)  
                # 获取文件的最后修改时间  
                mtime = os.path.getmtime(file_path)  
                # 如果这是最新的.swt文件，则更新latest_swt_file和latest_mtime  
                if mtime > latest_mtime:  
                    latest_swt_file = file_path  
                    latest_mtime = mtime  
            else:
                raise Exception('导出的文件后缀非SWT!')
  
    return latest_swt_file  

hwnd_title = dict()

def get_all_hwnd(hwnd,mouse):
    if win32gui.IsWindow(hwnd) and win32gui.IsWindowEnabled(hwnd) and win32gui.IsWindowVisible(hwnd):
        hwnd_title.update({hwnd:win32gui.GetWindowText(hwnd)})


def init_export_golden(handle_path):
    windows_hwnd = None
    print('start')
    while True:
        if not windows_hwnd:
            win32gui.EnumWindows(get_all_hwnd, 0)   
            for h,t in hwnd_title.items():
                if "- 投标管理 - 广联达预算计价" in t:
                # print(h, t)
                    windows_hwnd = h
            time.sleep(1)
            pg.hotkey("enter")
        else :
            break
        # 获取屏幕分辨率  
    print('end')
    screen_width = win32api.GetSystemMetrics(win32con.SM_CXSCREEN)
    screen_height = win32api.GetSystemMetrics(win32con.SM_CYSCREEN)

    # 获取窗口当前位置和大小  
    left, top, right, bottom = win32gui.GetWindowRect(windows_hwnd)
    window_width = right - left  
    window_height = bottom - top  

    # 计算新位置  
    new_left = (screen_width - window_width) // 2  
    new_top = (screen_height - window_height) // 2  

    # 移动窗口  
    win32gui.SetWindowPos(windows_hwnd, win32con.HWND_TOP, new_left, new_top, 1280, 760, 0)

    left, top, right, bottom = win32gui.GetWindowRect(windows_hwnd)

    print(str(left) + " " + str(top) + " " + str(right) + " " + str(bottom))
    pg.click((right - left) * (1 * (1.75 / 13)) + left, (bottom - top) * ((1.0 / 20) * 1) + top)
    print('11111')
    time.sleep(0.5)
    pg.click((right - left) * (1 * (1.75 / 18)) + left, (bottom - top) * ((1.0 / 10) * 1) + top)
    print('2222')
    time.sleep(0.5)
    pg.hotkey("esc")
    time.sleep(0.5)
    pg.hotkey("left")
    pg.hotkey("space")
    pg.typewrite(handle_path)
    time.sleep(0.5)
    pg.hotkey("enter")
    pg.hotkey("enter")
    pg.hotkey("tab")
    pg.typewrite("1")
    time.sleep(1)
    pg.hotkey("enter")

def close_software_golden():
    time.sleep(5)
    pids = psutil.pids()
    for pid in pids:
        try:
            p = psutil.Process(pid)
            process_name = p.name()
            if 'GCCP' in process_name or '广联达预算计价' in process_name:
            # 杀掉指定进程
            # print('kill process: name: %s - pid: %s' %(process_name, pid))

                find_kill = 'taskkill -f -pid %s' % pid
                os.popen(find_kill)
                # time.sleep(2)
                # os.popen(find_kill)
                sure =  win32gui.FindWindow(None, "确认")
                if sure:
                    win32gui.SendMessage(sure, win32con.WM_KEYDOWN, win32con.VK_RETURN, 0)
                    win32gui.SendMessage(sure, win32con.WM_KEYUP, win32con.VK_RETURN, 0)
                # time.sleep(2)
                save =  win32gui.FindWindow(None, "保存")
                if save:
                    win32gui.SendMessage(save, win32con.WM_KEYDOWN, win32con.VK_RETURN, 0)
                    win32gui.SendMessage(save, win32con.WM_KEYUP, win32con.VK_RETURN, 0)
        except Exception as e:
            print("捕获到错误")
            

def export_file_golden():
    time.sleep(1)
    hwnd = win32gui.FindWindow(None, "投标信息")
    left, top, right, bottom = win32gui.GetWindowRect(hwnd)
    screen_width = win32api.GetSystemMetrics(win32con.SM_CXSCREEN)  
    screen_height = win32api.GetSystemMetrics(win32con.SM_CYSCREEN)  
    window_width = right - left  
    window_height = bottom - top  

    # 计算新位置  
    new_left = (screen_width - window_width) // 2  
    new_top = (screen_height - window_height) // 2  

    set_foreground_window(hwnd)
    pg.hotkey("tab")
    pg.typewrite("1")
    pg.click((right - left) * (1 * (10 / 13)) + left, (bottom - top) * ((18.5 / 20) * 1) + top)

    time.sleep(1)
    # 移动窗口  
    # win32gui.SetWindowPos(hwnd, win32con.HWND_TOP, new_left, new_top, 551, 451, 0)
    tips =  win32gui.FindWindow(None, "提示")
    if tips:
        win32gui.SendMessage(tips, win32con.WM_CLOSE, 0, 0)
        time.sleep(1)
        # pg.hotkey("enter")
        pg.typewrite("1")
        pg.click((right - left) * (1 * (10 / 13)) + left, (bottom - top) * ((18.5 / 20) * 1) + top)
    # 移动窗口  
    # win32gui.SetWindowPos(hwnd, win32con.HWND_TOP, new_left, new_top, 551, 451, 0)
    time.sleep(1)
    tips2 =  win32gui.FindWindow(None, "提示")
    if tips2:
        win32gui.SendMessage(tips2, win32con.WM_CLOSE, 0, 0)
        time.sleep(1)
        # pg.hotkey("enter")
        pg.hotkey("tab")
        pg.typewrite("1")
        pg.hotkey("enter")
        pg.hotkey("down")
        pg.hotkey("enter")
        pg.click((right - left) * (1 * (10 / 13)) + left, (bottom - top) * ((18.5 / 20) * 1) + top)
    # pg.hotkey("enter")
    # 移动窗口  
    # win32gui.SetWindowPos(hwnd, win32con.HWND_TOP, new_left, new_top, 551, 451, 0)

    # pg.hotkey("enter")
    # time.sleep(0.5)

    # pg.hotkey("enter")
    # time.sleep(0.5)
    # pg.hotkey("enter")

    while True:
        time.sleep(5)
        # 导出成功
        success_hwnd = win32gui.FindWindow(None, "成功")
        if success_hwnd:
            app = Application(backend='uia').connect(handle=success_hwnd)
            dlg = app.window(title=win32gui.GetWindowText(success_hwnd))  

            # 遍历子控件，找到包含文本信息的Static控件  
            # 注意：这里假设我们知道Static控件的精确路径或可以通过某种方式唯一地识别它  
            # 在实际情况中，你可能需要遍历所有子控件并检查它们的属性来找到它  
            static_control = dlg.child_window(control_type="Text", found_index=1)  # found_index可能需要根据实际情况调整  

            text = static_control.window_text()
            print(text)
            match = re.search(r".:/.*?_投标书/" , text)
            if match:  
                directory = match.group(0)  
                print(directory)  
            else:  
                print("未找到匹配的目录地址")
            directory = directory + '电子投标书/'
            final_file = find_latest_swt_file_golden(directory)
            print(final_file)
            return final_file
        
def pick_first_file_golden(windows_hwnd):
    screen_width = win32api.GetSystemMetrics(win32con.SM_CXSCREEN)
    screen_height = win32api.GetSystemMetrics(win32con.SM_CYSCREEN)

    # 获取窗口当前位置和大小  
    left, top, right, bottom = win32gui.GetWindowRect(windows_hwnd)
    window_width = right - left  
    window_height = bottom - top  

    # 计算新位置  
    new_left = (screen_width - window_width) // 2  
    new_top = (screen_height - window_height) // 2  

    # 移动窗口  
    win32gui.SetWindowPos(windows_hwnd, win32con.HWND_TOP, new_left, new_top, 1280, 760, 0)

    left, top, right, bottom = win32gui.GetWindowRect(windows_hwnd)
    pg.doubleClick((right - left) * (0.5) + left, (bottom - top) * ((1.5 / 10) * 1) + top)

def open_file_golden():
    
    hwnd =  win32gui.FindWindow(None, "广联达云计价平台GCCP6.0")
    while True:
        if not hwnd:
            time.sleep(1)
            hwnd =  win32gui.FindWindow(None, "广联达云计价平台GCCP6.0")
        else:
            break


    set_foreground_window(hwnd)
    screen_width = win32api.GetSystemMetrics(win32con.SM_CXSCREEN)
    screen_height = win32api.GetSystemMetrics(win32con.SM_CYSCREEN)

    # 获取窗口当前位置和大小  
    left, top, right, bottom = win32gui.GetWindowRect(hwnd)
    window_width = right - left  
    window_height = bottom - top  

    # 计算新位置  
    new_left = (screen_width - window_width) // 2  
    new_top = (screen_height - window_height) // 2  

    # 移动窗口  
    win32gui.SetWindowPos(hwnd, win32con.HWND_TOP, new_left, new_top, 1280, 760, 0)
    app = Application(backend='uia').connect(handle=hwnd)
    dlg = app.window(title=win32gui.GetWindowText(hwnd))  
    button = dlg.child_window(title="本地文件", control_type="Button", found_index = 0)
    button.click_input()
    # print(dlg.print_ctrl_ids())
    button1 = dlg.child_window(title="本地文件", control_type="Button", found_index = 1)
    button1.click_input()
    button1 = dlg.child_window(title="本地文件", control_type="Button", found_index = 0)
    button1.click_input()
    edit = dlg.child_window(control_type="Edit", found_index = 0)
    edit.click_input()
    pg.hotkey("ctrl", "a")
    pg.typewrite("C")
    pg.hotkey("enter")
    pg.hotkey("enter")
    time.sleep(1)
    # print(dlg.print_control_identifiers())
    pick_first_file_golden(hwnd)
    edit.click_input()
    pg.hotkey("ctrl", "a")
    pg.typewrite("gloden_files")
    pg.hotkey("enter")
    pg.hotkey("enter")
    time.sleep(1)
    pick_first_file_golden(hwnd)
    edit.click_input()
    pg.hotkey("ctrl", "a")
    pg.hotkey("backspace")
    pg.hotkey("enter")
    pg.hotkey("enter")
    time.sleep(1)
    pick_first_file_golden(hwnd)
    time.sleep(5)
    sure =  win32gui.FindWindow(None, "确认")
    if sure:
        pg.hotkey("enter")
        win32gui.SendMessage(sure, win32con.WM_KEYDOWN, win32con.VK_RETURN, 0)
        win32gui.SendMessage(sure, win32con.WM_KEYUP, win32con.VK_RETURN, 0)
    tips = win32gui.FindWindow(None, "提示")
    if tips:
        app = Application(backend='uia').connect(handle=tips)
        dlg = app.window(title=win32gui.GetWindowText(tips))  
        # print(dlg.print_ctrl_ids())
        static_control = dlg.child_window(control_type="Text", found_index=3)  # found_index可能需要根据实际情况调整  
        text = static_control.window_text()
        raise Exception(text)

                    
    time.sleep(5)

# 导出成功
def export_success(id, file_name):
    url = '''http://127.0.0.1:9135/rpa/runSuccess'''
    data = {
        "id" : id,
        "file_name" : file_name
    }
    headers = {
        'Content-Type': 'application/json'
    }
    requests.post(url = url, data = json.dumps(data), headers= headers)


# 导出成功
def export_success_golden(id, file_name, file_path):
    url = '''http://127.0.0.1:9135/rpa/runSuccess'''
    data = {
        "id" : id,
        "file_name" : file_name,
        "file_path" : file_path
    }
    headers = {
        'Content-Type': 'application/json'
    }
    requests.post(url = url, data = json.dumps(data), headers= headers)


# 异常处理
def export_failed(id, errorMsg):
    url = '''http://127.0.0.1:9135/rpa/runFailed'''
    data = {
        "id" : id,
        "errMsg": errorMsg
    }
    headers = {
        'Content-Type': 'application/json'
    }
    requests.post(url = url, data = json.dumps(data), headers=headers)

def delete_files_in_directory(directory):  
    for filename in os.listdir(directory):  
        file_path = os.path.join(directory, filename)  
        try:  
            if os.path.isfile(file_path) or os.path.islink(file_path):
                os.unlink(file_path)  
            elif os.path.isdir(file_path): 
                delete_files_in_directory(file_path)
                os.rmdir(file_path)
            # 这里不处理目录，所以不需要elif os.path.isdir(file_path):  
        except Exception as e:  
            print(f'Failed to delete {file_path}. Reason: {e}') 

pg.FAILSAFE = False 

# 程序被唤起 参数为文件本地地址 文件id
dir_path = sys.argv[1]
need_export_file_name = sys.argv[2]
id = int(sys.argv[3])


# 获取盘符
drive_letter = dir_path[0]


# 获取临时交换区目录地址
user_bak_dir = drive_letter + r':\THSware\清单计价2016 深圳网络标准版\UserBak'
user_data_dir = drive_letter + r':\THSware\清单计价2016 深圳网络标准版\UserData\深圳'
swareTmp_dir = drive_letter + r':\THSware\清单计价2016 深圳网络标准版\Bin\$SwareTmp$'
auto_bak_dir = drive_letter + r':\THSware\清单计价2016 深圳网络标准版\AutoBak'
handle_path = drive_letter + r':\gloden_files'

file_ext_list_swire = ['qdg3', 'qdg4', 'qdy3', 'qdy4']
file_ext_list_golden = ['gbq6', 'gbq5', 'gbq4', 'gtb4', 'gzb4']



try:
    close_software()
    close_software_golden()
    delete_files_in_directory(user_bak_dir)
    delete_files_in_directory(user_data_dir)
    delete_files_in_directory(swareTmp_dir)
    delete_files_in_directory(auto_bak_dir)
    delete_files_in_directory(handle_path)
    file_pre, file_ext = check_qdy_qdg(need_export_file_name)
    software_path = 'C:\\'
    time.sleep(1)
    # 桌面软件地址
        
    if file_ext in file_ext_list_swire :
        try:
            # 打开导出桌面软件
            open_software(software_path)
            # 关闭提示
            close_tips()
            # 关闭新建向导
            hwnd = 0
            if (file_ext == 'qdy3' or file_ext == 'qdy4') :
                hwnd = qdy_open_file('新建建设项目', dir_path + need_export_file_name)
            else :
                close_tutor()
                hwnd = open_file(dir_path + need_export_file_name)
            check_sure_upgrade()
            check_version()
            check_precision()
            # 恢复软件默认设置
            # reset_softWare_Default()
            # check_project_number_is_null()
            # 执行点击流程导出软件
            export_file(hwnd, file_ext)
            fill_author_info()
            xml_file_name = do_export(id, hwnd, 0)
            check_success(id ,hwnd, 0)
            # print(xml_file_name)
            # 导出成功
            time.sleep(5)
            export_success(id, xml_file_name)
            close_software()
            # 检测到导出成功窗口后5秒关闭软件
        except Exception as e:
            close_software()
            export_failed(id, str(e))
            time.sleep(5)
    else:
        try :
            time.sleep(5)
            shutil.copy(dir_path + need_export_file_name, handle_path)
            open_software_golden(software_path)
            # time.sleep(3)
            open_file_golden()
            init_export_golden(handle_path)
            file = export_file_golden()
            directory_path, file_name = os.path.split(file)  
            export_success_golden(id, file_path= file, file_name = file_name)
            close_software_golden()
            time.sleep(5)
        except Exception as e:
            close_software_golden()
            export_failed(id, str(e))
            # print(str(e))
            time.sleep(5)
        delete_files_in_directory(handle_path)
except Exception as e:
    print(str(e))
    export_failed(id, str(e))
    close_software_golden()
    close_software()